#!/usr/bin/env bash
# Copyright (c) 2021 maminjie <maminjie2@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0


# get_list strings/file
#   Get list from string list or list file
# Params:
#   strings - string list, like: "a b c ..."
#   file - list file, like:
#           f1) echo "a b c d" > f1
#           f2) for i in $list; do echo "$i" >> f2; done
# Example:
#   ---------test.sh---------
#   lst=$(get_list "$1")
#   for i in $lst; do
#       ...
#   done
#
#   function test() {
#       local pkgs=$(get_list "$1")
#       for pkg in $pkgs; do
#           ....
#       done
#   }
#
#   test "x y z"
#   -------------------------
#   > bash test.sh "a b c d"
#
get_list() {
    local lst=""

    if [ -f "$1" ]; then
        lst=$(cat "$1")
    else
        lst=$1
    fi

    echo "$lst"
}

readonly BALL_TYPES=".tar .tgz .tar.gz .zip .tar.bz2 .tar.xz .jar"

# uncompress type ball
#   Uncompress the ball of the specified type
# Params:
#   type - in BALL_TYPES
#   ball - the name of ball file
# Example:
#   -------------------------
#   for t in $BALL_TYPES; do
#       local balls=$(ls *$t 2>/dev/null)
#       if [ -n "$balls"]; then
#           for b in $balls; do
#               uncompress $t $b
#           done
#       fi
#   done
#   -------------------------
uncompress() {
    local type=$1
    local ball=$2

    case "$type" in
        ".tar")
            tar -f "$ball"
            ;;
        ".tgz"|".tar.gz")
            tar -zxf "$ball"
            ;;
        ".zip")
            unzip -q "$ball"
            ;;
        ".tar.bz2")
            tar -jxf "$ball"
            ;;
        ".tar.xz")
            tar -Jxf "$ball"
            ;;
        ".jar")
            unzip -q "$ball" -d "${ball%.*}"
            ;;
        *)
            echo "$type is not supported!"
            echo "$BALL_TYPES are supported!"
            ;;
    esac
}